import { Form, Modal, Select, Input, message, Spin } from 'antd'
import React, { useEffect, useMemo } from 'react'
import type { DictItem, orderType } from '@/types'
import { useWatch } from 'antd/es/form/Form'
import http from '@/utils/request'

interface FormItemType {
  dispatchType: number,
  teamId: string,
  userCode: string,
  orderComment: ''
}

const DispatchOrder: React.FC<{
  isOpen: boolean,
  order?: orderType,
  teamList: DictItem[],
  teamType?: string,
  close: () => void
  success: () => void
}> = ({ isOpen, order, teamList, close, success, teamType }) => {
  const [personList, setPersonList] = React.useState<DictItem[]>([])
  const [loading, setLoading] = React.useState(false)

  const isBatch = useMemo(() => {
    const str = order?.id || ''
    return str.split(',').length > 1
  }, [order])

  const getPersonList = (val: any) => {
    http.post('/disp/sys/user/page', {
      pageNum: 1,
      pageSize: 9999,
      teamId: val,
      status: 'Enable'
    }).then(res => {
      setPersonList((res.data.list || []).map((item: {
        userCode: string,
        username: string,
      }) => {
        return {
          value: item.userCode,
          label: item.username
        }
      }))
    })
  }
  const [dispatchForm] = Form.useForm()
  const dispatchType = useWatch('dispatchType', dispatchForm)

  useEffect(() => {
    dispatchForm.resetFields()
    dispatchForm.setFieldsValue({ teamId: teamType === 'Biz' ? order?.bizTeamId : order?.seatTeamId })
    order && getPersonList(order.seatTeamId)
  }, [isOpen, order])

  const handleTypeChange = () => {
    dispatchForm.setFieldsValue({ teamId: order?.seatTeamId })
  }

  const handleOk = () => {
    dispatchForm.validateFields().then((values) => {
      const { teamId, userCode, dispatchType, orderComment } = values
      const doRequest = () => {
        // 指派到个人
        if (dispatchType === 1) {
          return http.post('/disp/biz/order/assignSeatTeamUser', {
            id: order?.id,
            orderComment,
            userCode
          })
        }
        const url =
          isBatch ?
            // 批量指派到业务团队
            '/disp/biz/order/batchAssignBizTeam' :
            // 单个指派到业务团队或坐席团队
            teamType === 'Biz' ?
              '/disp/biz/order/assignTeam' :
              '/disp/biz/order/assignSeatTeam'
        return http.post(url, {
          [isBatch ? 'orderIds' : 'id']: isBatch ? order?.id?.split(',') : order?.id,
          orderComment,
          teamId
        })
      }
      setLoading(true)
      doRequest().then(() => {
        message.success('指派成功！')
        success()
      }).catch(err => {
        message.error(err.msg || '指派失败')
        close()
      }).finally(() => {
        setLoading(false)
      })
    })
  }

  const options = useMemo(() => {
    return teamList.filter(item => item.teamType === teamType)
  }, [teamType, teamList])

  return (
    <Spin spinning={loading}>
      <Modal title={(isBatch ? '批量' : '') + (teamType === 'Biz' ? '指派订单' : '坐席转派')}
        destroyOnHidden={true}
        open={isOpen}
        onOk={handleOk}
        onCancel={close}>
        <Form
          form={dispatchForm}
          initialValues={{ dispatchType: 0 }}
          style={{ marginTop: 20 }}
          layout="vertical">
          <Form.Item<FormItemType>
            label="分配给"
            name="dispatchType"
            rules={[{ required: true, message: '请选择分配类型' }]}
          >
            {/* PC业务只能分配到团队 */}
            <Select
              allowClear
              placeholder="请选择"
              style={{ width: '100%' }}
              disabled={teamType === 'Biz'}
              onChange={handleTypeChange}
              options={[{
                value: 0,
                label: '团队'
              }, {
                value: 1,
                label: '团队成员'
              }]}
            />
          </Form.Item>
          <Form.Item<FormItemType>
            label={teamType === 'Biz' ? '业务团队' : '坐席团队'}
            name="teamId"
            rules={[{ required: true, message: '请选择团队' }]}
          >
            <Select
              disabled={dispatchType === 1}
              allowClear
              placeholder="请选择"
              style={{ width: '100%' }}
              onChange={getPersonList}
              options={options}
            />
          </Form.Item>
          {dispatchType === 1 && (
            <Form.Item<FormItemType>
              label="业务负责人"
              name="userCode"
              rules={[{ required: true, message: '请选择业务负责人' }]}
            >
              <Select
                allowClear
                placeholder="请选择"
                style={{ width: '100%' }}
                options={personList}
              />
            </Form.Item>
          )}
          <Form.Item<FormItemType>
            label="备注"
            name="orderComment"
            rules={[{ required: true, message: '请输入备注' }]}
          >
            <Input placeholder="请输入" allowClear style={{ width: '100%' }}/>
          </Form.Item>
        </Form>
      </Modal>
    </Spin>
  )
}

export default DispatchOrder